<template>
  <div class="margin-container-list">
    <div class="header">
      <div>活动名称：{{entity.title}}</div>
      <div class="mar-t-6">
        <span>活动时间：{{entity.startTime}} - {{entity.endTime}}</span>
      </div>
    </div>
    <div class="pad-t-30 pad-r-30 flex-between total-row">
      <div class="align-c height-172 mar-l-20 flex-item shadow-box">
        <div class="font-36 color-price">{{ entity.totalPrice }}</div>
        <div class="font-14 font-color-9 mar-t-30">合计活动销售额(元)</div>
      </div>
      <div class="align-c height-172 mar-l-20 flex-item shadow-box">
        <div class="font-36 color-price" @click="orderDetail"><a style="text-decoration:blink">{{ entity.orderNum }}</a>
        </div>
        <div class="font-14 font-color-9 mar-t-30">合计活动订单数(笔)</div>
      </div>
      <div class="align-c height-172 mar-l-20 flex-item shadow-box">
        <div class="font-36 color-price" v-if="entity.orderNum != 0">{{ (entity.totalPrice / entity.orderNum).toFixed(2) }}
        </div>
        <div class="font-36 color-price" v-else>0</div>
        <div class="font-14 font-color-9 mar-t-30">活动客单价(元)</div>
      </div>
    </div>
    <!--表格-->
    <div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="entityList" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中" style="width: 100%">
          <el-table-column min-width="250px" label="商品">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.imageUrl" class="user-avatar"></label>
                <div class="font-14 pad-l-10">
                  <div>{{scope.row.title}}</div>
                  <template v-if="scope.row.categoryName">
                    <div>
                      <span class="category-style">[{{scope.row.categoryName}}]</span>
                      <el-tag class="mar-l-10" size="mini" v-if="scope.row.skuFlag == 1" effect="light">多规格</el-tag>
                    </div>
                  </template>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="现有库存"  v-if="entity.activityType === 0">
            <template slot-scope="scope">
              <template v-if="scope.row.stock <= scope.row.warnStock">
                <span style="color: #dd1100">{{scope.row.stock - scope.row.stockInUse}}</span>
              </template>
              <template v-else>
                {{scope.row.stock - scope.row.stockInUse}}
              </template>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="活动库存" v-if="entity.activityType === 2">
            <template slot-scope="scope">
              <span>{{scope.row.stock}}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="entity.activityType === 2" width="120px" label="限购(件)" prop="limitNum"/>
          <el-table-column width="120px" label="零售价">
            <template slot-scope="scope">
              ￥{{scope.row.sellPrice}}
            </template>
          </el-table-column>
          <el-table-column width="120px" :label="entity.activityType === 0 ? '活动价(元)' : '团购价(元)'">
            <template slot-scope="scope">
              <span v-if="scope.row.skuFlag == 0">￥{{scope.row.promotionPrice}}</span>
              <span v-if="scope.row.skuFlag == 1">
                <el-button type="primary" plain @click="orderDetailSku(scope.row)">查看</el-button>
              </span>
            </template>
          </el-table-column>
          <el-table-column width="250px" label="活动分销佣金(元)" v-if="entity.activityType === 0">
            <template slot-scope="scope">
              <span>微客佣金：￥{{scope.row.distributeIncome}}</span><br />
              <span>顾客分销佣金：￥{{scope.row.shareMemberIncome}}</span>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="团长佣金(元)" v-if="entity.activityType === 2">
            <template slot-scope="scope">
              <span>{{scope.row.totalCommission}}</span><br />
            </template>
          </el-table-column>
          <el-table-column width="150px" label="销售件数" v-if="entity.activityType === 2">
            <template slot-scope="scope">
              <span>{{scope.row.salesNum}}</span><br />
            </template>
          </el-table-column>
          <el-table-column width="150px" label="活动销售额(元)" v-if="entity.activityType === 0">
            <template slot-scope="scope">
              <span v-if="scope.row.skuFlag == 1">
                合计：￥{{scope.row.totalPrice}}
                <el-button type="primary" plain @click="orderDetailSku(scope.row)">查看</el-button>
              </span>
              <span v-if="scope.row.skuFlag == 0">￥{{scope.row.totalPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="活动销售额(元)" v-if="entity.activityType === 2">
            <template slot-scope="scope">
              <!-- 社区团购订单暂时不跳转 -->
              <span>{{scope.row.totalPrice ? scope.row.totalPrice : 0}}</span>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="活动订单笔数(笔)" v-if="entity.activityType === 0">
            <template slot-scope="scope">
              <span v-if="scope.row.skuFlag == 1">
                <a v-if="scope.row.orderNum" style="text-decoration: underline"
                  @click="orderDetailSku(scope.row)">合计：<span>{{scope.row.orderNum}}</span></a><br
                  v-if="scope.row.orderNum" />
                <el-button type="primary" plain @click="orderDetailSku(scope.row)">查看</el-button>
              </span>
              <span v-if="scope.row.skuFlag == 0 && entity.activityType !== 2"><a v-if="scope.row.orderNum"
                  style="text-decoration: underline"
                  @click="orderDetail()">合计：<span>{{scope.row.orderNum}}</span></a></span>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="活动订单笔数(笔)" v-if="entity.activityType === 2">
            <template slot-scope="scope">
              <el-button type="text" @click="orderDetail()">{{scope.row.orderNum ? scope.row.orderNum : 0}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination mar-b-0 pad-b-20">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="entityListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="entityListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!--库存展示-->
    <el-dialog title="多规格商品" :visible.sync="financeVisible" :close-on-press-escape="true" center>
      <div
        class="el-table el-table--fit el-table--border el-table--enable-row-hover el-table--medium el-table--scrollable-x">
        <div class="el-table__body-wrapper">
          <el-table ref="multipleTable" :data="skuList" v-loading="listLoading" element-loading-text="加载中"
            style="width: 100%" border height="500px">
            <el-table-column min-width="90px" label="规格" prop="skuDetail"></el-table-column>
            <el-table-column width="100px" label="库存" prop="stock" v-if="entity.activityType === 0"></el-table-column>
            <el-table-column width="120px" label="零售价">
              <template slot-scope="scope">
                ￥{{scope.row.price}}
              </template>
            </el-table-column>
            <el-table-column width="120px" :label="entity.activityType === 0 ? '活动价' : '团购价'">
              <template slot-scope="scope">
                ￥{{scope.row.promotionPrice}}
              </template>
            </el-table-column>
            <el-table-column width="120px" label="活动销售额">
              <template slot-scope="scope">
                ￥{{scope.row.totalPrice}}
              </template>
            </el-table-column>
            <el-table-column width="120px" label="活动订单数">
              <template slot-scope="scope">
                <span v-if="scope.row.orderNum == 0">{{scope.row.orderNum}}</span>
                <a @click="orderDetail()" v-if="scope.row.orderNum !== 0"
                  style="color: #2d8cf0; text-decoration: underline">{{scope.row.orderNum}}</a>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="financeVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    pagingGoodsActive,
    getGoodsDetail
  } from '@/api/sell/promotionGoods'
  import {
    countPromotionOrder
  } from '@/api/sell/promotion'
  export default {
    data() {
      return {
        entity: {
          title: '',
          startTime: '',
          endTime: '',
          totalPrice: 0,
          orderNum: 0
        },
        skuList: [],
        promotionId: '',
        entityList: [],
        total: null,
        listLoading: false,
        financeVisible: false,
        entityListQuery: {
          currentPage: 1,
          size: 10,
          promotionId: this.promotionId
        }
      }
    },
    // 初始化页面
    created() {
      const queryParams = this.getCurrentPage().query
      if (queryParams.promotionId) {
        this.promotionId = queryParams.promotionId
        this.initEntity()
        this.initEntityList()
      }
    },
    methods: {
      // 更改当前页面大小
      handleSizeChange(val) {
        this.entityListQuery.size = val
        this.initEntityList()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.entityListQuery.currentPage = val
        this.initEntityList()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      orderDetail() {
        if (this.entity.activityType === 2) {
          this.$router.push({
            path: '/community/order/index',
            query: {
              promotionId: this.promotionId,
              orderStatus: '100',
              showStatOrder: '0'
            }
          })
          return
        }
        this.$router.push({
          path: '/order/order/index',
          query: {
            promotionId: this.promotionId,
            orderStatus: '100',
            showStatOrder: '0'
          }
        })
      },
      orderDetailSku(row) {
        var data = {
          goodsId: row.goodsId,
          promotionId: this.promotionId,
          userId: this.getEnterpriseId()
        }
        getGoodsDetail(data).then((response) => {
          if (response.isError) return
          this.skuList = response.data
          this.financeVisible = true
        })
      },
      // 数列展示
      qualityInit() {
        const arrQta = []
        const itemQta = this.form.qualityData
        if (itemQta.length === 1) {
          const skuPropId = itemQta[0].skuPropId
          const skuPropName = itemQta[0].skuPropName
          const skuPropValueList = itemQta[0].skuPropValueList
          for (let i = 0; i < skuPropValueList.length; i++) {
            skuPropValueList[i].skuPropId = skuPropId
            skuPropValueList[i].skuPropName = skuPropName
          }
          this.form.singleTable = skuPropValueList
        } else {
          const skuCache = {}
          if (this.form.qualityTable.length > 0) {
            this.form.qualityTable.forEach(row => {
              let item = skuCache
              for (const col in row) {
                if (row[col].skuPropValueId) {
                  if (!item[row[col].skuPropValueId]) {
                    item[row[col].skuPropValueId] = {
                      ...row
                    }
                  }
                  item = item[row[col].skuPropValueId]
                }
              }
            })
          }
          this.form.qualityTable = []
          for (let i = 0; i < itemQta.length; i++) {
            const skuPropId = itemQta[i].skuPropId
            const skuPropName = itemQta[i].skuPropName
            for (let j = 0; j < itemQta[i].skuPropValueList.length; j++) {
              itemQta[i].skuPropValueList[j].skuPropId = skuPropId
              itemQta[i].skuPropValueList[j].skuPropName = skuPropName
            }
            arrQta.push(itemQta[i].skuPropValueList)
          }
          this.form.qualityTable = this.$utils.descartes(arrQta)
          if (this.form.qualityTable.length > 0) {
            this.form.qualityTable.forEach((row, index) => {
              let item = skuCache
              for (const col in row) {
                if (row[col].skuPropValueId) {
                  if (item[row[col].skuPropValueId]) {
                    item = item[row[col].skuPropValueId]
                  }
                }
              }
              // 新增子规格，设置原来的sku的值
              if (item.supplierPrice) {
                this.$set(this.form.qualityTable[index], 'supplierPrice', item.supplierPrice)
              }
              if (item.goodsBarCode) {
                this.$set(this.form.qualityTable[index], 'goodsBarCode', item.goodsBarCode)
              }
              if (item.stock) {
                this.$set(this.form.qualityTable[index], 'stock', item.stock)
              }
              if (item.skuId) {
                this.$set(this.form.qualityTable[index], 'skuId', item.skuId)
              }
              if (item.imageUrl) {
                this.$set(this.form.qualityTable[index], 'imageUrl', item.imageUrl)
              }
            })
          }
        }
      },
      setQualityTable(dataTable) {
        const skuValueMap = new Map()
        for (let i = 0; i < dataTable.length; i++) {
          skuValueMap.set(dataTable[i].skuValueIds, dataTable[i])
        }
        const qualityTable = this.form.qualityTable
        const qualityData = this.form.qualityData

        if (qualityData.length === 1) {
          const skuPropValueList = qualityData[0].skuPropValueList
          const skuPropId = qualityData[0].skuPropId
          const skuPropName = qualityData[0].skuPropName

          for (let i = 0; i < skuPropValueList.length; i++) {
            skuPropValueList[i].skuPropId = skuPropId
            skuPropValueList[i].skuPropName = skuPropName
            const skuPropValueId = skuPropValueList[i].skuPropValueId
            const array = []
            array.push(skuPropValueId)
            const skuValueKey = array.sort().toString()
            const skuValueObj = skuValueMap.get(skuValueKey)
            skuPropValueList[i].imageUrl = this.$utils.isExist(skuValueObj.imageUrl) ? skuValueObj.imageUrl
              : ''
            skuPropValueList[i].price = this.$utils.isExist(skuValueObj.price) ? skuValueObj.price : ''
            skuPropValueList[i].supplyPrice = this.$utils.isExist(skuValueObj.supplyPrice) ? skuValueObj
              .supplyPrice : ''
            skuPropValueList[i].promotionPrice = this.$utils.isExist(skuValueObj.promotionPrice) ? skuValueObj
              .promotionPrice : ''
            skuPropValueList[i].orderNum = this.$utils.isExist(skuValueObj.orderNum) ? skuValueObj.orderNum
              : ''
            skuPropValueList[i].stock = this.$utils.isExist(skuValueObj.stock) ? skuValueObj.stock : ''
            skuPropValueList[i].goodsBarCode = this.$utils.isExist(skuValueObj.goodsBarCode) ? skuValueObj
              .goodsBarCode : ''
            skuPropValueList[i].warnStock = this.$utils.isExist(skuValueObj.warnStock) ? skuValueObj
              .warnStock : ''
          }

          this.form.singleTable = skuPropValueList
        } else {
          const array = []
          for (let i = 0; i < qualityTable.length; i++) {
            const item = qualityTable[i]
            const skuPropValueList = []
            for (const key in item) {
              if (this.$utils.isExist(item[key].skuPropId)) {
                const skuPropValueId = item[key].skuPropValueId
                skuPropValueList.push(skuPropValueId)
              }
            }
            const obj = {}
            const skuValueKey = skuPropValueList.sort().toString()
            const skuValueObj = skuValueMap.get(skuValueKey)
            if (skuValueObj != null) {
              for (const key in item) {
                obj[key] = item[key]
              }
              obj.imageUrl = this.$utils.isExist(skuValueObj.imageUrl) ? skuValueObj.imageUrl : ''
              obj.price = this.$utils.isExist(skuValueObj.price) ? skuValueObj.price : ''
              obj.supplyPrice = this.$utils.isExist(skuValueObj.supplyPrice) ? skuValueObj.supplyPrice : ''
              obj.promotionPrice = this.$utils.isExist(skuValueObj.promotionPrice) ? skuValueObj
                .promotionPrice : ''
              obj.orderNum = this.$utils.isExist(skuValueObj.orderNum) ? skuValueObj.orderNum : ''
              obj.stock = this.$utils.isExist(skuValueObj.stock) ? skuValueObj.stock : ''
              obj.skuId = this.$utils.isExist(skuValueObj.skuId) ? skuValueObj.skuId : ''
              obj.supplierPrice = this.$utils.isExist(skuValueObj.supplierPrice) ? skuValueObj
                .supplierPrice : ''
              obj.warnStock = this.$utils.isExist(skuValueObj.warnStock) ? skuValueObj.warnStock : ''
              array.push(obj)
            } else {
              console.log('sku异常' + skuValueKey)
            }
          }
          this.form.qualityTable = array
        }
      },
      getID(length) {
        const ids = this.ids
        const id = -parseInt(Math.round(Math.random() * 100000000))
        if (ids.indexOf(id) > 0) {
          this.getID()
        } else {
          ids.push(id)
          this.ids = ids
          return id
        }
      },
      initEntity() {
        countPromotionOrder(this.promotionId).then(response => {
          if (response.isError) return
          this.entity = response.data
        })
      },
      initEntityList() {
        this.listLoading = true
        this.entityListQuery.promotionId = this.promotionId
        pagingGoodsActive(this.entityListQuery).then(response => {
          if (response.isError) return
          this.entityList = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  .margin-container-list {
    min-height: 100%;
    background: #FAFAFA;
    margin: 0;
    padding: 20px 20px 0;
  }

  .header {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    height: 76px;
    padding-left: 20px;
    font-size: 16px;
    color: #666;
    background: #E2F0FF;
  }

  .shadow-box {
    background: white;
    box-shadow: 0 0 15px rgba(154, 154, 154, 0.21);
  }

  .color-price {
    color: #409EFF;
  }

  .total-row {
    padding-bottom: 36px;
    background: white;

    .align-c {
      justify-content: center;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .top-operate {
    margin-bottom: 0;
  }

  .search-item {
    display: flex;
    align-items: center;
    padding-bottom: 15px;
    border-bottom: solid 1px #E4E7ED;

    >div,
    .el-cascader {
      margin-right: 10px;
    }

    .el-input {
      width: 300px;
    }
  }

  .btn-search {
    height: 60px;
    display: flex;
    align-items: center;
  }

  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .category-style {
    color: #3abbdb;
  }

  .gray-bar {
    background: #e4e4e4;
    padding: 20px;
    margin-bottom: 20px;
    width: 80%;
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }
</style>
